<template>
  <div class="header-bg">
    <picture>
      <source srcset="@/assets/img/game/header_bg.webp" />
      <img class="bg-img" src="@/assets/img/game/header_bg.jpg" alt="" fetchpriority="high" />
    </picture>
    <bubble />
    <div class="header">
      <div class="first-part">
        <div class="title-box" v-click-outside="closePopupOnClickOutside">
          <div @click="toggleDiv" ref="divElementer" class="title">
            <div>
              {{ getAllGame[currentGame]?.['lotteryName'] }}
            </div>
            <ArrowAnimate
              ref="arrowAnimate"
              :color="`#ffffff`"
              :size="'0.2rem'"
              :style="{ 'margin-left': '0.08rem' }"
            />
          </div>

          <collapse v-model:value="shows">
            <div class="games">
              <template v-for="(item, key) in getAllGame">
                <div
                  v-if="item.isValidity !== 3"
                  class="li"
                  @click="selectGame(item, key)"
                  :key="key"
                  :class="{ active: currentGame === key, maintenance: item.isValidity !== 1 }"
                >
                  <span>{{ item?.['lotteryName'] }}</span>
                  <span v-if="item.isValidity !== 1">({{ getTxt(item['isValidity']) }})</span>
                </div>
              </template>
            </div>
          </collapse>
        </div>
        <Option />
      </div>
      <div class="second-part">
        <div class="left">
          <Period :periodsNumber="renderData.periodsNumber" :drawingStatus="drawingStatus" />

          <div>
            <Countdown :formattingTime="formattingTime" :countdownText="countdownText" />
          </div>
        </div>
        <div class="right" id="headerWinNumber" />

        <div class="mipai-box" @click="appStore.setIsMipai">
          <div v-if="appStore.isMipai" class="mipai-open" />
          <div v-else class="mipai-close" />
        </div>
      </div>
      <Tabs />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onActivated,
  onMounted,
  onBeforeUnmount,
  computed,
  unref,
  watch,
  ComputedRef,
  defineAsyncComponent,
} from 'vue'
import ArrowAnimate from '@/components/arrow-animate.vue'
import { setGameDefaultKey } from '@/utils'
import Countdown from './countdown.vue'

import { useGameStore } from '@/stores/game'
import { GAME_STATUS_CODE, LotterCodeEnum } from '@/enum'
import { findCurrentWinNum as findCurrentWinNumApi } from '@/api'
import { useRouter } from 'vue-router'
import { utc8timestamp } from '@/utils/dayjs'
// import Option from './option.vue'
import Tabs from './tabs.vue'
import { useAppStore } from '@/stores/app'

const bubble = defineAsyncComponent(() => import('./bubble.vue'))
const Period = defineAsyncComponent(() => import('./period.vue'))
const collapse = defineAsyncComponent(() => import('@/components/collapse.vue'))
const Option = defineAsyncComponent(() => import('./option.vue'))

const miTime = 5000
let timeouts = [] // setTimeout 队列， 清除副作用函数

const shows = ref(false),
  renderData = ref<any>({}),
  endTime = ref(0),
  closeTime = ref(0),
  startTime = ref(0),
  findCurrentWinNumInterval = ref(null),
  countdownText = ref(''),
  currentTime = ref(new Date().getTime()),
  interval = ref(null),
  arrowAnimate = ref(null),
  divElementer = ref(null),
  blindTime = ref()

const gameStore = useGameStore()
// const investStore = useInvestStore()
const router = useRouter()

const appStore = useAppStore()

onActivated(() => {
  timeouts = []
})

onMounted(() => {
  findCurrentWinNum()
})

onBeforeUnmount(() => {
  clearTime()
})

const currentGame = computed(() => gameStore.currentGame) as ComputedRef<LotterCodeEnum>

const getAllGame = computed(() => gameStore.allGame)

const drawingStatus = computed(() => gameStore.drawingStatus)

const formattingTime = computed(() => {
  let _startTime = unref(startTime)

  let _endTime = unref(endTime) // 结束时间，会在每个阶段都变动

  const _currentTime = unref(currentTime)

  if (_currentTime > _endTime) return { progress: '100', date: ['--', '--', '--'] }
  // 计算已经过的时间和总时间
  const elapsedTime = _currentTime - _startTime < 0 ? 0 : _currentTime - _startTime
  const totalTime = _endTime - _startTime //时间总和
  const remainingTime = (_endTime - _currentTime) / 1000 //剩余时间总秒数
  // 计算时间进度比例
  const progress = (elapsedTime / totalTime) * 100
  // 创建一个日期对象
  const hours = Math.floor(remainingTime / 3600)
  const minutes = Math.floor((remainingTime % 3600) / 60)
  const remainingSeconds = Math.floor(remainingTime % 60)
  // 使用 padStart 将时、分、秒格式化为两位数
  const formattedHours = String(hours).padStart(2, '0')
  const formattedMinutes = String(minutes).padStart(2, '0')
  const formattedSeconds = String(remainingSeconds).padStart(2, '0')
  return { progress: progress, date: [formattedHours, formattedMinutes, formattedSeconds] }
})

watch(
  drawingStatus,
  (newValue) => {
    switch (newValue.code * 1) {
      case GAME_STATUS_CODE.kaijiang.code:
        clearTime()
        findCurrentWinNum()
        break
      case GAME_STATUS_CODE.mi.code:
        endTime.value = new Date().getTime() + miTime
        countdownText.value = '咪牌'
        break
      case GAME_STATUS_CODE.kaipan.code:
        endTime.value = closeTime.value
        countdownText.value = '下注'
        break
      default:
        countdownText.value = ''
        break
    }
  },
  { deep: true },
)

const closePopupOnClickOutside = () => {
  arrowAnimate.value?.unRotateArrow?.()
  shows.value = false
}

// 显示游戏弹窗
const toggleDiv = () => {
  if (!shows.value) {
    arrowAnimate.value?.rotateArrow?.()
    shows.value = true
  } else {
    closePopupOnClickOutside()
  }
}

// 选择游戏
const selectGame = (item, key) => {
  if (item.isValidity !== 1) return
  // this.active = index;
  shows.value = !shows.value
  arrowAnimate.value.unRotateArrow()
  setGameDefaultKey(key)
  gameStore.setCurrentGame(key)
  router.push('/game/' + key.toLowerCase())
  endTime.value = 0
  findCurrentWinNum()
}

// 初始化开奖数据
const findCurrentWinNum = async () => {
  const res = await findCurrentWinNumApi({ lotteryCode: unref(currentGame) })
  renderData.value = res.data[0]
  gameStore.setLatestGameData(renderData)
  // this.startTime = new Date(this.renderData.autoDrawingDate).getTime(); //开盘时间
  startTime.value = new Date().getTime() //开盘时间,因为接口时间不准，所以用当前时间
  blindTime.value = getTime(renderData.value.drawingDate) //开奖时间
  closeTime.value = getTime(renderData.value.autoCloseDate) //封盘时间
  remainingTime() // 处理倒计时剩余时间
  setStatus() // 设置快彩开盘状态
}

const getTime = (str) => {
  return utc8timestamp(str)
}

// 处理倒计时剩余时间
const remainingTime = () => {
  if (interval.value) clearInterval(interval.value)
  interval.value = setInterval(() => {
    currentTime.value = new Date().getTime()
  }, 1000)
}

// 更新开盘状态
const setStatus = () => {
  switch (renderData.value.status) {
    case GAME_STATUS_CODE.kaipan.code:
      endTime.value = closeTime.value
      countdownText.value = '下注'
      break
    case GAME_STATUS_CODE.mi.code:
      endTime.value = new Date().getTime() + miTime
      countdownText.value = '咪牌'
      break
    default:
      countdownText.value = ''
      break
  }
  handleSlowGameStatus() //慢彩没有socket推送，设置未来的状态。
  gameStore.setDrawingStatus(renderData.value.status)
}

// 处理慢彩开盘状态
const handleSlowGameStatus = () => {
  // 清除之前的副作用函数
  for (const id of timeouts) {
    clearTimeout(id)
  }
  const currentTime = new Date().getTime()
  const _closeTime = closeTime.value //封盘时间
  const _blindTime = blindTime.value //咪牌时间
  // 慢彩没有socket推送，在固定时间处理状态
  const slowMap = {
    [_closeTime - currentTime]: GAME_STATUS_CODE.fengpan.code, //到这时间后要封盘
    [_blindTime - currentTime]: GAME_STATUS_CODE.mi.code, //咪牌时间，到这个时间后后台已经开奖，前端要咪牌
    [_blindTime - currentTime + miTime]: GAME_STATUS_CODE.kaijiang.code, //到这时间后，咪牌结束，前端要开奖
  }
  const slowGameList = [LotterCodeEnum.xglhc, LotterCodeEnum.qxc]
  if (slowGameList.includes(unref(currentGame))) {
    for (let key in slowMap) {
      const _key = Number(key)
      if (_key > 0) {
        const id = setTimeout(() => {
          gameStore.setDrawingStatus(slowMap[key])
        }, _key)
        timeouts.push(id)
      }
    }
  }
}

// 清除定时器
const clearTime = () => {
  clearInterval(interval.value)
  clearInterval(findCurrentWinNumInterval.value)
  // 清除之前的副作用函数
  for (const id of timeouts) {
    clearTimeout(id)
  }
}

const getTxt = (val) => {
  // 0:维护 1:正常 2:休市 3:隐藏
  if (val === 2) return '未开盘'
  if (val === 0) return '维护中'
  return ''
}
</script>

<style scoped lang="less">
.header-bg {
  position: relative;
  //background: url('@/assets/img/game/header_bg.jpg') center no-repeat;
  //background-size: cover;
  .bg-img {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 0;
  }
}

.header {
  height: 159px;
  padding: 0 10px 10px;
  box-sizing: border-box;
}

.first-part {
  display: flex;
  justify-content: space-between;
  height: 41px;
  box-sizing: border-box;
  padding-top: 7px;
  line-height: 1;
}

.title-box {
  display: flex;
  align-items: center;
  padding: 0 10px;
  position: relative;
}

.title {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #fff;
  font-weight: 600;
}

.games {
  position: absolute;
  left: 0;
  top: 39px;
  min-width: 100px;
  width: max-content;
  border-radius: 4px;
  z-index: 999;
  color: rgba(181, 188, 255, 1);
  background-color: #272c5d;
  box-shadow: 0px 0px 4px 0px rgba(36, 5, 5, 0.25);

  .maintenance {
    > span:nth-of-type(1) {
      font-size: 12px;
      color: #a1a2a8;
    }

    > span:nth-of-type(2) {
      font-size: 11px;
      color: #ff5b5b;
    }
  }

  .li {
    height: 38px;
    font-size: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .active {
    background: rgba(101, 90, 227, 1);
    color: white;
  }

  .li:first-child {
    border-top-right-radius: 4px;
    border-top-left-radius: 4px;
  }

  .li:last-child {
    border-bottom-right-radius: 4px;
    border-bottom-left-radius: 4px;
  }
}

.second-part {
  position: relative;
  display: flex;
  margin-bottom: 9px;
  width: 100%;
  height: 74px;
  box-sizing: border-box;
  padding: 10px;
  justify-content: space-between;

  .left {
    width: 124px;
  }

  .right {
    min-width: 190px;
  }
}

.second-part:after {
  content: '';
  position: absolute;
  width: 95%;
  height: 2px;
  //background-color: #c2e8ff;
  //border: 1px solid #c2e8ff;
  transform: scaleY(0.5);
  border-radius: 20px;
  opacity: 0.5;
  left: 10px;
  bottom: -2px;
  background-image: linear-gradient(45deg, transparent, #f183f1, #00ffff, transparent);
  background-size: 400% 400%;
  animation: glowing 15s linear infinite;
  animation-direction: alternate;
}

.mipai-box {
  width: 72px;
  height: 20px;
  position: absolute;
  top: 10px;
  right: 11px;

  .mipai-close {
    width: 100%;
    height: 100%;
    background: url('@/assets/img/game/eye_close.png') center center no-repeat;
    background-size: contain;
  }

  .mipai-open {
    width: 100%;
    height: 100%;
    background: url('@/assets/img/game/eye_open.png') center center no-repeat;
    background-size: contain;
  }
}

@keyframes glowing {
  0% {
    background-position: 0 0;
  }

  50% {
    background-position: 400% 0;
    opacity: 0.1;
  }

  100% {
    background-position: 0 0;
    opacity: 0.3;
  }
}
</style>
